package com.learning.servlet2x.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * ClassName: ObjectAttributeListener
 * Description: 在线人数监听器：监听 ServletRequest 创建与销毁。统计单用户，访问次数
 * 1、用户每次请求 request 都会执行 requestInitialized 方法
 * 2、request 处理完毕自动销毁前执行 requestDestroyed 方法
 * 3、如果一个页面有很多图片，则会触发多次 requestInitialized 方法
 * <p>
 * Date: 2014-12-10 22:25 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class OnlineRequestListener implements ServletRequestListener {

    /**
     * 每一个请求都会触发
     *
     * @param event
     */
    @Override
    public void requestInitialized(ServletRequestEvent event) {

        HttpServletRequest request = (HttpServletRequest) event.getServletRequest();

        HttpSession session = request.getSession(true);

        // 记录客户端 IP 地址
        session.setAttribute("ip", request.getRemoteAddr());

        // 记录访问次数，只记录访问 .html, .do, .jsp, .action 的累计次数
        String uri = request.getRequestURI();
        String[] suffix = {".html", ".do", ".jsp", ".action"};
        for (int i = 0; i < suffix.length; i++) {
            if (uri.endsWith(suffix[i])) {
                // 访问的制定后缀页面
                break;
            }
            if (i == suffix.length - 1) {
                return;
            }
        }

        Integer activeTimes = (Integer) session.getAttribute("activeTimes");

        if (activeTimes == null) {
            activeTimes = 0;
        }

        // 更新访问次数
        session.setAttribute("activeTimes", activeTimes + 1);
    }


    @Override
    public void requestDestroyed(ServletRequestEvent event) {
    }
}
